<template>
  <div class="">
    <a-form
      ref="form"
      :model="form"
      size="small"
      :disabled="disabled"
      class="h360"
    >
      <!-- <el-form-item
        label="获取经纬度"
        prop="longitude"
      >
        <el-row>
          <el-col
            :span="11"
            class="pl0 pr0"
          >
            <el-input
              readonly
              v-model="form.longitude"
              placeholder="请输入经度"
            ></el-input>
          </el-col>
          <el-col
            :span="2"
            class="line s-tac"
          > - </el-col>
          <el-col
            :span="11"
            class="pl0 pr0"
          >
            <el-input
              readonly
              v-model="form.latitude"
              placeholder="请输入纬度"
            ></el-input>
          </el-col>
        </el-row>

      </el-form-item> -->
      <a-form-item label="">
        <div>
          <div
            id="map-container"
            class="s-posr"
            style="width:100%;height:380px;"
          >
          </div>
          <el-autocomplete
            v-model="form.address"
            class="w360 s-posa z100 t20 l20"
            popper-class="autoAddressClass"
            :fetch-suggestions="querySearchAsync"
            :trigger-on-focus="false"
            placeholder="详细地址"
            clearable
            @select="handleSelect"
          >
            <template slot-scope="{ item }">
              <i class="el-icon-search fl mgr10" />
              <div style="overflow:hidden;">
                <div class="title">{{ item.title }}</div>
                <span class="address ellipsis">{{ item.address }}</span>
              </div>
            </template>
          </el-autocomplete>
        </div>

      </a-form-item>
    </a-form>
  </div>
</template>

<script>
/* eslint-disable */
import loadBMap from "@/utils/loadBMap.js";
export default {
  data() {
    return {
      form: {
        address: "", // 详细地址
        longitude: "",
        latitude: "",
        addrPoint: {
          // 详细地址经纬度
          lng: 0,
          lat: 0,
        },
      },
      rules: {
        address: [
          {
            required: true,
            message: "请输入详细地址",
            trigger: "blur",
          },
        ],
        longitude: [
          {
            required: true,
            message: "请选择经纬度",
            trigger: "blur",
          },
        ],
        latitude: [
          {
            required: true,
            message: "请选择经纬度",
            trigger: "blur",
          },
        ],
      },
      map: "", // 地图实例
      mk: "", // Marker实例
      locationPoint: null,
    };
  },
  props: {
    disabled: {
      type: Boolean,
      default: function () {
        return false;
      },
    },
  },
  async mounted() {
    this.handleInit({})
  },
  methods: {
    async handleInit(_row) {
      let _this = this;
      await loadBMap("IjO56EW0Vq2gjagGOTyGr2Ug"); // 加载引入BMap

      this.$nextTick(() => {
        if (_row) {
          this.form = {
            address: _row.address || "", // 详细地址
            longitude: _row.longitude || "",
            latitude: _row.latitude || "",
            addrPoint: {
              // 详细地址经纬度
              lng: _row.longitude || "",
              lat: _row.latitude || "",
            },
          };
          console.log("_row", _row);
        }
        this.initMap();
      });
    },
    // 初始化地图
    initMap() {
      var that = this;
      // 1、挂载地图
      this.map = new BMap.Map("map-container", { enableMapClick: false });
      console.log("that.form", that.form);
      var point = new BMap.Point(
        that.form.longitude ? that.form.longitude : 120.3185818508172,
        that.form.latitude ? that.form.latitude : 31.498809578738538
      );
      this.map.centerAndZoom(point, 19);
      // 3、设置图像标注并绑定拖拽标注结束后事件
      this.mk = new BMap.Marker(point, { enableDragging: true });
      this.map.addOverlay(this.mk);
      this.mk.addEventListener("dragend", function (e) {
        that.getAddrByPoint(e.point);
      });
      // 4、添加（右上角）平移缩放控件
      this.map.addControl(
        new BMap.NavigationControl({
          anchor: BMAP_ANCHOR_TOP_RIGHT,
          type: BMAP_NAVIGATION_CONTROL_SMALL,
        })
      );
      // 5、添加（左下角）定位控件
      var geolocationControl = new BMap.GeolocationControl({
        anchor: BMAP_ANCHOR_BOTTOM_LEFT,
      });
      geolocationControl.addEventListener("locationSuccess", function (e) {
        that.getAddrByPoint(e.point);
      });
      geolocationControl.addEventListener("locationError", function (e) {
        // alert(e.message)
      });
      this.map.addControl(geolocationControl);
      // 6、浏览器定位
      //   this.geolocation();
      // 7、绑定点击地图任意点事件
      this.map.addEventListener("click", function (e) {
        that.getAddrByPoint(e.point);
      });
    },
    // 获取两点间的距离
    getDistancs(pointA, pointB) {
      return this.map.getDistance(pointA, pointB).toFixed(2);
    },
    // 浏览器定位函数
    geolocation() {
      var that = this;
      var geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(
        function (res) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            that.getAddrByPoint(res.point);
            that.locationPoint = res.point;
          } else {
            that.locationPoint = new BMap.Point(113.3324436, 23.1315381);
          }
        },
        { enableHighAccuracy: true }
      );
    },
    // 2、逆地址解析函数
    getAddrByPoint(point) {
      var that = this;
      var geco = new BMap.Geocoder();
      console.log("point", point);
      geco.getLocation(point, function (res) {
        console.log("res", res);
        that.mk.setPosition(point);
        that.map.panTo(point);
        that.form.address = res.address;
        that.form.addrPoint = point;
        that.form.longitude = point.lng;
        that.form.latitude = point.lat;
        // that.$emit("getBMap", that.form);
        that.onSubmit();
      });
    },
    // 8-1、地址搜索
    querySearchAsync(str, cb) {
      var options = {
        onSearchComplete: function (res) {
          var s = [];
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < res.getCurrentNumPois(); i++) {
              s.push(res.getPoi(i));
            }
            cb(s);
          } else {
            cb(s);
          }
        },
      };
      var local = new BMap.LocalSearch(this.map, options);
      local.search(str);
    },
    // 8-2、选择地址
    handleSelect(item) {
      console.log("item", item);
      this.form.address = item.address + item.title;
      this.form.addrPoint = item.point;
      this.form.longitude = item.point.lng;
      this.form.latitude = item.point.lat;
      // this.$emit("getBMap", this.form);
      this.map.clearOverlays();
      this.mk = new BMap.Marker(item.point);
      this.map.addOverlay(this.mk);
      this.map.panTo(item.point);
      this.onSubmit();
    },
    onSubmit() {
      this.$emit("getMap", this.form);
    },
  },
};
</script>

<style lang="scss" scoped>
.autoAddressClass {
  li {
    i.el-icon-search {
      margin-top: 11px;
    }
    .mgr10 {
      margin-right: 10px;
    }
    .title {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .address {
      line-height: 1;
      font-size: 12px;
      color: #b4b4b4;
      margin-bottom: 5px;
    }
  }
}
</style>